<template>
    <view class="content">
        <navView navTitle="新增用户" titleColor="#fff" :isBack="true"></navView>
        <view class="form-container">
            <!-- 抬头名称 -->
            <view class="form-item">
                <text class="label">姓名:</text>
                <input class="input" type="text" v-model="formData.name" placeholder="请输入姓名" />
            </view>
            <!-- 岗位 -->
            <view class="form-item">
                <text class="label">岗位:</text>
                <uni-data-select style="width: 70%;" v-model="formData.role"
                    :localdata="positionOptions"></uni-data-select>
            </view>
            <!-- 身份证号 -->
            <view class="form-item">
                <text class="label">身份证号:</text>
                <input class="input" type="text" v-model="formData.idnumber" placeholder="请输入身份证号" />
            </view>

            <!-- 学历 -->
            <view class="form-item">
                <text class="label">学历:</text>
                <uni-data-select style="width: 70%;" v-model="formData.educational"
                    :localdata="eduOptions"></uni-data-select>
            </view>

            <!-- 联系电话 -->
            <view class="form-item">
                <text class="label">联系电话:</text>
                <input class="input" type="number" v-model="formData.mobile" placeholder="请输入联系电话" />
            </view>

            <!-- 紧急联系电话 -->
            <view class="form-item">
                <text class="label">紧急联系电话:</text>
                <input class="input" type="text" v-model="formData.emergencymobile" placeholder="请输入紧急联系电话" />
            </view>

            <!-- 是否签订合同 -->
            <view class="form-item">
                <text class="label">试用期合同是否签订:</text>
                <uni-data-select style="width: 70%;" v-model="formData.is_trial"
                    :localdata="isJoinOptions"></uni-data-select>
            </view>

            <!-- 签订时间 -->
            <view class="form-item">
                <text class="label">签订时间:</text>
                <picker mode="date" @change="trialBindDateChange">
                    <view class="input">{{ formData.trialdate || '请选择日期' }}</view>
                </picker>
            </view>

            <view class="data-statistics">
                <view class="title">
                    <view class="tiao"></view>
                    扫描件
                </view>
                <view class="root">
                    <view class="list-item" v-for="(item, index) in trialfile" :key="index">
                        <image class="file-icon" src="https://hfd.bjlzkj.com/static/list/file.png" />
                        <view class="option">
                            <view class="file-info">
                                <view class="file-title">{{ item.name }}</view>
                                <view class="file-time"></view>
                            </view>
                            <view class="action-buttons">
                                <button class="download-button" @click="handleDownload(item.url)">下载</button>
                                <button class="view-button" @click="handleView(item.url)">查看</button>
                            </view>
                        </view>
                    </view>
                </view>
                <button class="btn upload-btn" @click="uploadFile(1)">上传附件</button>
            </view>

            <!-- 是否签订正式合同 -->
            <view class="form-item">
                <text class="label">是否签订正式合同:</text>
                <uni-data-select style="width: 70%;" v-model="formData.is_join"
                    :localdata="isJoinOptions"></uni-data-select>
            </view>

            <!-- 签订日期 -->
            <view class="form-item">
                <text class="label">签订日期:</text>
                <picker mode="date" @change="joinBindDateChange">
                    <view class="input">{{ formData.joiningdate || '请选择日期' }}</view>
                </picker>
            </view>

            <view class="data-statistics">
                <view class="title">
                    <view class="tiao"></view>
                    扫描件
                </view>
                <view class="root">
                    <view class="list-item" v-for="(item, index) in joinfile" :key="index">
                        <image class="file-icon" src="https://hfd.bjlzkj.com/static/list/file.png" />
                        <view class="option">
                            <view class="file-info">
                                <view class="file-title">{{ item.name }}</view>
                                <view class="file-time"></view>
                            </view>
                            <view class="action-buttons">
                                <button class="download-button" @click="handleDownload(item.url)">下载</button>
                                <button class="view-button" @click="handleView(item.url)">查看</button>
                            </view>
                        </view>
                    </view>
                </view>
                <button class="btn upload-btn" @click="uploadFile(2)">上传附件</button>
            </view>
            <view class="data-statistics">
                <view class="title">
                    <view class="tiao"></view>
                    入职资料
                </view>
                <view class="root">
                    <view class="list-item" v-for="(item, index) in entryfile" :key="index">
                        <image class="file-icon" src="https://hfd.bjlzkj.com/static/list/file.png" />
                        <view class="option">
                            <view class="file-info">
                                <view class="file-title">{{ item.name }}</view>
                                <view class="file-time"></view>
                            </view>
                            <view class="action-buttons">
                                <button class="download-button" @click="handleDownload(item.url)">下载</button>
                                <button class="view-button" @click="handleView(item.url)">查看</button>
                            </view>
                        </view>
                    </view>
                </view>
                <button class="btn upload-btn" @click="uploadFile(3)">上传附件</button>
            </view>
            <!-- 薪资 -->
            <view class="form-item">
                <text class="label">薪资:</text>
                <input class="input" type="number" v-model="formData.salary" placeholder="请输入薪资" />
            </view>
            <!-- 提交按钮 -->
            <button class="submit-btn" @click="handleSubmit">提交</button>
        </view>
    </view>
</template>

<script>
import download from '@/util/filesdownload.js'; //
export default {
    data() {
        return {
            formData: {
                name: '',
                role: 2,
                idnumber: '',
                educational: '',
                mobile: '',
                emergencymobile: '',
                joiningdate: '',
                trialdate: '',
                is_join: 0,
                is_trial:0,
                joinfile: "",
                trialfile: "",
                entryfile: "",
                salary: ''
            },
            joinfile: [],
            trialfile: [],
            entryfile: [],
            positionOptions: [
                { value: 3, text: "销售" },
                { value: 4, text: "技术" },
                { value: 5, text: "财务" },
                { value: 6, text: "行政" }
            ],
            eduOptions: [
                { value: '小学', text: "小学" },
                { value: '初中', text: "初中" },
                { value: '高中', text: "高中" },
                { value: '大专', text: "大专" },
                { value: '本科', text: "本科" },
                { value: '研究生', text: "研究生" },
                { value: '博士', text: "博士" }
            ],
            isJoinOptions: [
                { value: 1, text: "是" },
                { value: 0, text: "否" },
            ]
        };
    },
    onShow() {

    },
    methods: {
        handleSubmit() {
            console.log('表单数据:', this.formData);
            uni.showModal({
                title: '操作确认',
                content: '确认要新增该用户吗？',
                success: (res) => {
                    if (res.confirm) {                        
                        // 处理files（添加数组存在性校验）
                        this.formData.joinfile = ""; // 新增重置操作
                        this.formData.trialfile = ""; // 新增重置操作
                        this.formData.entryfile = ""; // 新增重置操作
                        if (this.joinfile && this.joinfile.length > 0) {
                            this.joinfile.forEach(item => {
                                this.formData.joinfile += item.flie_url + ',';
                            });
                            this.formData.joinfile = this.formData.joinfile.replace(/,$/, '');
                        }
                        if (this.trialfile && this.trialfile.length > 0) {
                            this.trialfile.forEach(item => {
                                console.log(item)
                                this.formData.trialfile += item.flie_url + ',';
                            });
                            this.formData.trialfile = this.formData.trialfile.replace(/,$/, '');
                        }
                        if (this.entryfile && this.entryfile.length > 0) {
                            this.entryfile.forEach(item => {
                                console.log(item)
                                this.formData.entryfile += item.flie_url + ',';
                            });
                            this.formData.entryfile = this.formData.entryfile.replace(/,$/, '');
                        }
                        console.log(this.formData,'formData')
                        this.$request('/addons/qingdong/staff/createStaff', 'POST', this.formData).then(res => {
                            if (res.code == 1) {
                                uni.showToast({ title: '新增用户成功', icon: 'success' });  // 新增失败提示
                                setTimeout(() => {
                                    uni.navigateBack()
                                }, 2000)					
                            } else {
                                uni.showToast({ title: res.msg, icon: 'none' });
                            }
                        });
                    } else {
                        uni.showToast({ title: '已取消', icon: 'fail' });
                    }
                }
            });
        },
        // 日期选择
        joinBindDateChange(e) {
            this.formData.joiningdate = e.detail.value;
        },
        // 日期选择
        trialBindDateChange(e) {
            this.formData.trialdate = e.detail.value;
        },
        // 文件上传
        async uploadFile(type) {
            const res = await uni.chooseFile({
                count: 1,
                extension: ['pdf', 'doc', 'docx', 'jpg', 'png']
            });
            if (res.tempFiles[0]) {
                this.formData[type] = res.tempFiles[0].path;
                // 实际开发中需要调用上传接口
            }
        },
        handleDownload(url) {
            download.downloadFun(url);
        },
        handleView(url) {
            // 检查文件是否已下载
            uni.showLoading({ title: '正在打开...' });  // 新增加载提示
            uni.downloadFile({
                url: url,
                success: function (res) {
                    var filePath = res.tempFilePath;
                    uni.openDocument({
                        filePath: encodeURI(filePath),
                        showMenu: true,
                        success: function (res) {
                            uni.hideLoading();  // 隐藏加载提示
                            console.log('打开文档成功', res);
                        },
                        fail: function (err) {
                            uni.hideLoading();  // 隐藏加载提示
                            console.error('打开文档失败', err);
                        }
                    });
                },
                fail: (err) => {
                    uni.hideLoading();  // 隐藏加载提示
                    console.error('下载失败', err);
                    uni.showToast({ title: '文件下载失败', icon: 'none' });  // 新增失败提示
                }
            });
        },
        // 去上传按钮点击事件
        uploadFile(sw) {
            const token = uni.getStorageSync('user_token');
            uni.chooseImage({
                count: 9,
                type: 'all',
                success: async (res) => {
                    const result = uni.uploadFile({
                        url: 'https://hfd.bjlzkj.com/addons/qingdong/common/upload',
                        filePath: res.tempFilePaths[0],  // 改用tempFilePaths数组中的路径
                        name: 'file',  // 后端接收文件的参数名
                        formData: {
                            category: this.category,  // 添加分类参数
                        },
                        header: {
                            'Content-Type': 'application/json',
                            'token': token // 新增token请求头
                        },
                        success: (uploadFileRes) => {
                            console.log('上传结果:', uploadFileRes);
                            uni.showToast({ title: '上传成功' });
                            // 新增数据解析校验
                            try {
                                const resData = JSON.parse(uploadFileRes.data);
                                if (resData && resData.data && resData.data.url) {
                                    if (sw == 1) {
                                        this.trialfile = [
                                            ...(this.trialfile || []),  // 添加空数组保护
                                            {
                                                name: resData.data.url.split('/').pop(),
                                                url: resData.data.url,
                                                flie_url: resData.data.flie_url
                                            }
                                        ];
                                    } else if(sw == 2) {
                                        this.joinfile = [
                                            ...(this.joinfile || []),  // 添加空数组保护
                                            {
                                                name: resData.data.url.split('/').pop(),
                                                url: resData.data.url,
                                                flie_url: resData.data.flie_url
                                            }
                                        ];
                                    }else{
                                        this.entryfile = [
                                            ...(this.entryfile || []),  // 添加空数组保护
                                            {
                                                name: resData.data.url.split('/').pop(),
                                                url: resData.data.url,
                                                flie_url: resData.data.flie_url
                                            }
                                        ];
                                    }
                                } else {
                                    console.error('接口返回数据异常:', resData);
                                }
                            } catch (e) {
                                console.error('数据解析失败:', e);
                            }
                        },
                        fail: (err) => {
                            console.error('上传失败:', err);
                            uni.showToast({ title: '上传失败', icon: 'none' });
                        },
                    })
                }
            });
        }
    }
};
</script>

<style scoped lang="scss">
.content {
    .form-container {
        background-color: #fff;
        border-radius: 16rpx;
        padding: 0 20rpx;
    }

    .form-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #ccc;
    }

    .data-statistics {
        background-color: #ffffff;
        border-radius: 20rpx;
        margin-bottom: 20rpx;

        .title {
            font-size: 28rpx;
            font-weight: bold;
            display: flex;
            align-items: center;
            border-bottom: 1rpx solid #ccc;
            padding: 24rpx 12rpx;

            .tiao {
                width: 6rpx;
                height: 22rpx;
                background: #1B87E8;
                border-radius: 8rpx 8rpx 8rpx 8rpx;
                margin-right: 10rpx;
            }
        }

        .times {
            padding: 10rpx 0rpx;

            .uni-icons {
                margin-right: 10rpx;
            }

            .time:first-child {
                border: 0;
            }

            .time {
                padding: 20rpx 20rpx;
                display: flex;
                align-items: center;
                justify-content: space-between;
                color: #333333;
                font-size: 24rpx;
                border-top: 1rpx solid #ccc;

                .right {
                    display: flex;
                    align-items: center;
                }
            }
        }

        .btn {
            border-radius: 10rpx;
            /* 增大圆角 */
            border: 1rpx solid #008EFF;
            color: #008EFF;
            font-size: 26rpx;
            /* 增大字体 */
            background: transparent;
            padding: 15rpx 30rpx;
            /* 调整内边距 */
            transition: all 0.3s ease;
            /* 添加过渡效果 */
            margin-right: 15rpx;
            /* 添加按钮间距 */
            /* 新增 */
            margin: 20rpx auto 0;
            /* 修改 */
            width: 93%;
        }

        /* 上传附件按钮样式 */
        .upload-btn:hover {
            background-color: rgba(0, 142, 255, 0.1);
            border-color: #0077e6;
            align-self: flex-start; // 新增（左对齐）

        }

        /* 完成按钮样式 */
        .complete-btn {
            background-color: #008EFF;
            color: white;
            border: none;
            box-shadow: 0 4rpx 8rpx rgba(0, 142, 255, 0.3);
            margin-top: 10rpx;
            display: block;
            /* 新增 */
            margin: 20rpx auto 0;
            /* 修改 */
            width: 93%;
            /* 可选，控制按钮宽度 */
        }

        .complete-btn:hover {
            background-color: #0077e6;
            box-shadow: 0 6rpx 12rpx rgba(0, 142, 255, 0.4);
            transform: translateY(-2rpx);
        }
    }

    .root {
        padding: 20rpx;
        display: flex; // 新增
        flex-direction: column; // 新增
        gap: 20rpx; // 新增

        .list-item {
            display: flex;
            align-items: center;
            padding: 20rpx 0;
            position: relative;
            justify-content: space-between;

            &:last-child {
                border: 0;
            }

            .file-icon {
                width: 120rpx;
                height: 120rpx;
            }

            .option {
                width: 80%;

                .file-info {
                    flex: 1;

                    .file-title {
                        font-size: 24rpx;
                        font-weight: bold;
                        color: #333;
                    }

                    .file-time {
                        font-size: 24rpx;
                        color: #999;
                        margin-top: 8rpx;
                    }
                }

                .action-buttons {
                    width: 100%;
                    display: flex;
                    justify-content: flex-end;
                    margin-top: 20rpx;

                    .download-button {
                        width: 158rpx;
                        height: 57rpx;
                        border-radius: 58rpx 58rpx 58rpx 58rpx;
                        border: 4rpx solid #008EFF;
                        font-size: 20rpx;
                        color: #008EFF;
                        background: #fff;
                        margin: 0;
                    }

                    .view-button {
                        width: 158rpx;
                        height: 57rpx;
                        border-radius: 58rpx 58rpx 58rpx 58rpx;
                        border: 4rpx solid #008EFF;
                        font-size: 20rpx;
                        color: #fff;
                        background: #008EFF;
                        margin: 0;
                        margin-left: 20rpx;
                    }
                }
            }
        }
    }

    .label {
        font-size: 32rpx;
        color: #333;
        width: 200rpx;
    }

    .radio-group {
        display: flex;
        flex-direction: column;
    }

    .radio-group label {
        margin-bottom: 10rpx;
    }

    .input {
        flex: 1;
        height: 80rpx;
        padding: 0 20rpx;
        font-size: 32rpx;
        border: none;
        text-align: right;
        border-radius: 10rpx;
    }

    .submit-btn {
        margin-top: 60rpx;
        width: 95%;
        background-color: #0081ff;
        color: white;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        border-radius: 50rpx;
        font-size: 32rpx;        
        bottom: 30rpx;
        
    }

    ::v-deep .uni-select {
        border: none;
    }

    ::v-deep .uni-select__input-text {
        text-align: right;
        padding-right: 30rpx;
    }
}
</style>